package com.atguigu.gulimall.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.to.SocialUser;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVO;
import com.atguigu.gulimall.auth.component.OauthComponent;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.service.IOauthService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author : wenchao.long
 * @date : Created in 2021/8/10 11:28 周二
 * @description :
 */
@Service
@AllArgsConstructor
@Slf4j
public class OauthServiceImpl implements IOauthService {

    private final OauthComponent oauthComponent;

    private final MemberFeignService memberFeignService;

    @Override
    public String weibo(String code, HttpSession session) {
        // 1. 根据code换取accessToken
        HttpResponse response = oauthComponent.weiboOauth(code);
        if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
            // 获取到了token
            try {
                String json = EntityUtils.toString(response.getEntity());
                SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
                log.info("user:" + socialUser);

                // 知道当前是哪个社交用户
                // 1. 当前用户如果第一次进网站 自动注册进来(为当前社交用户生成一个会员信息账号)
                // 登录或者注册 用户
                R r = memberFeignService.oauthLogin(socialUser);
                if (r.getCode() == 0) {
                    MemberResponseVO vo = r.getData(new TypeReference<MemberResponseVO>() {
                    });
                    log.info("登录成功,用户信息:" + vo);

                    // 1. 第一次使用session 命令浏览器保存卡号
                    // JSESSIONID这个cookie
                    // 子域之间 gulimall.com auth.gulimall.com order.gulimall.com
                    // 发卡的时候 即使是子域系统发的卡 也能让父域直接使用

                    // TODO 1. 默认发的令牌 session=xxx 作用域 当前域 (解决子域session共享问题)
                    // TODO 2. 使用json的序列化方式来序列化对象数据到redis
                    session.setAttribute(AuthServerConstant.LOGIN_USER, vo);

                    // 2. 登录成功就调回首页
                    return "redirect:http://gulimall.com";
                }
                return "redirect:http://auth.gulimall.com/login.html";
            } catch (IOException e) {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }

    @Override
    public String gitee(String code) {
        HttpResponse httpResponse = oauthComponent.giteeOauth(code);
        return null;
    }
}
